package com.sky.config;

import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

//使用DeepSeek中问题解决方案
/*
1.打开服务：
bash:"ollama serve"

2.确认Ollama服务状态
使用以下命令检查Ollama服务是否在运行：
bash: "netstat -ano | findstr :11434"

3.检查模型加载状态
确认模型deepseek-r1:7b已正确加载：
bash:"ollama list"
如果模型未加载，重新加载模型：
bash: "ollama pull deepseek-r1:7b"

4.关闭防火墙
*/
//使用方法可见：src/test/java/com/youy/Test1.java
public class DeepSeek {
    static class DeepSeekResponse {
        private String model;
        private String created_at;
        private String response;

        // Getters
        public String getResponse() {
            return response;
        }
    }
    static class RequestBodyData {
        String model = "deepseek-r1:7b"; // 确认模型名称
        String prompt;//问题内容
        boolean stream = false; // 关闭流式输出
    }
    private static final String API_URL = "http://localhost:11434/api/generate";
    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final Gson gson = new Gson();

    public String answer (String problem,Boolean think) throws IOException{
        //调整OkHttp的超时设置至60秒：
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(60, TimeUnit.SECONDS)     // 读取超时
                .build();
        RequestBodyData requestBody = new RequestBodyData();
        requestBody.prompt = problem;
        String json = gson.toJson(requestBody);

        Request request = new Request.Builder()
                .url(API_URL)
                .post(RequestBody.create(json, JSON))
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                // 解析错误信息
                String errorBody = response.body().string();
                System.err.println("HTTP " + response.code() + " 错误: " + errorBody);
                throw new IOException("请求失败: " + errorBody);
            }
            //解析响应体
            String responseBody=response.body().string();
            DeepSeekResponse ollamaResponse=gson.fromJson(responseBody,DeepSeekResponse.class);
            String rawResponse = ollamaResponse.getResponse();

            if(think){
                // 去除开头的""及后续空白符（如换行符、空格等）
                String cleanedResponse = rawResponse.replaceFirst("^\\s*", "");
                //去掉* # - 符号
                String resultString=cleanedResponse.replace("*","").trim();
                String resultString1=resultString.replace("","").trim();
                String resultString2=resultString.replace("#","").trim();
                String resultString3=resultString2.replace("-","").trim();
                //去掉deepseek思考过程<think>......</think>
                int s=resultString3.indexOf("<think>");
                int e=resultString3.lastIndexOf(">");
                String resultString4=resultString3;
                if(s!=-1&&e!=-1&&s<e){
                    resultString4=resultString3.substring(1,s+1)+resultString3.substring(e+1);
                }
                //返回回答的内容
                return resultString4;
            }
            return rawResponse;
        }
    }
}
